<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>书籍详情</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='styles copy.css') }}">
</head>
<body>
    <div class="container">
        <!-- 顶部导航栏 -->
        <div class="navbar">
            <a href="/" class="btn" aria-label="返回">
                <img src="{{ url_for('static', filename='icons/返回箭头_详情页 (1).svg') }}" alt="返回">
            </a>
        </div>

        <!-- 书籍详情内容区 -->
        <div class="book-detail">
            <img src="{{ book.image }}" alt="{{ book.title }}" class="book-image">
            <h1>{{ book.title }}</h1>
            <p class="author">作者：{{ book.author }}</p>
            <div class="book-info">
                <div class="average-rating">
                    <h2>评分：</h2>
                    <a1 id="averageRatingValue">--</a1> 
                </div>
                <div class="epub-reader">
                    <h2>在线阅读</h2>
                    <a href="{{ url_for('epub_reader', book_id=book.id) }}" class="btn">阅读电子书</a>
                </div>
            </div>
            
            <div class="book-info1">
                <div class="description-header">
                    <label for="jianjie" class="jianjie">简介：</label>
                </div>
                <p class="description" id="jianjie">{{ book.description }}</p>
            </div>

            <button id="toggleDescription" class="btn">更多</button>
        </div>

        <!-- 评论区 -->
        <div class="comments-section1">
            <div class="comments-header1">
                <label class="comments-title1">热门评论</label>
                <button id="moreReviews" class="more-reviews-btn1">更多书评</button>
            </div>
        </div>

        <div class="comments-section"></div>
            <div id="noCommentsMessage" class="no-comments-message">暂时还没有评论哦</div>
            <div id="commentsContainer" class="comments-container"></div>
            <button id="addCommentButton" class="add-comment-btn">点击评论</button>
        </div>
        
        <!-- 更多书评弹窗 -->
        <div id="moreReviewsModal" class="modal hidden">
            <div class="modal-content">
                <h3>全部书评</h3>
                <div id="allCommentsContainer"></div>
                <button id="closeReviewsModal" class="modal-btn cancel">关闭</button>
            </div>
        </div>

        <!-- 添加评论弹窗 -->
        <div id="addCommentModal" class="modal hidden">
            <div class="modal-content">
                <h3>添加评论</h3>
                <label for="ratingInput">评分 (1~5)：</label>
                <input id="ratingInput" type="number" min="1" max="5" value="5" />
                <textarea id="commentInput" placeholder="请输入评论内容"></textarea>
                <div class="modal-actions">
                    <button id="submitReviewBtn" class="modal-btn">提交评论</button>
                    <button id="closeModal" class="modal-btn cancel">取消</button>
                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript 代码 -->
    <script>
        document.addEventListener("DOMContentLoaded", () => {
            const addCommentButton = document.getElementById("addCommentButton");
            const addCommentModal = document.getElementById("addCommentModal");
            const submitReviewBtn = document.getElementById("submitReviewBtn");
            const closeModal = document.getElementById("closeModal");
            const commentsContainer = document.getElementById("commentsContainer");
            const noCommentsMessage = document.getElementById("noCommentsMessage");
            const moreReviewsBtn = document.getElementById("moreReviews");
            const moreReviewsModal = document.getElementById("moreReviewsModal");
            const closeReviewsModal = document.getElementById("closeReviewsModal");
            const allCommentsContainer = document.getElementById("allCommentsContainer");
            const ratingInput = document.getElementById("ratingInput");
            const commentInput = document.getElementById("commentInput");
            const bookId = {{ book.id }}; // 动态渲染书籍 ID
            const averageRatingValue = document.getElementById("averageRatingValue");

            // 页面加载时获取评论并渲染
            fetch(`/api/reviews/${bookId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        renderReviews(data.reviews); // 渲染评论
                        if (data.average_rating !== undefined) {
                            averageRatingValue.textContent = data.average_rating.toFixed(1); // 设置平均评分
                        } else {
                            averageRatingValue.textContent = "暂无";
                        }
                    }
                })
                .catch(err => {
                    console.error("获取评论失败", err);
                });

            // 渲染评论
            function renderReviews(reviews) {
                commentsContainer.innerHTML = "";
                if (reviews.length === 0) {
                    noCommentsMessage.style.display = "block";
                } else {
                    noCommentsMessage.style.display = "none";

                    const visibleReviews = reviews.slice(0, 3); // 显示前三条评论
                    visibleReviews.forEach((item) => {
                        // 处理时间格式
                        let formattedDate;
                        try {
                            // 如果时间戳是秒级，乘以 1000 转换为毫秒
                            const timestamp = typeof item.created_at === "number" && item.created_at.toString().length === 10
                                ? item.created_at * 1000
                                : item.created_at;
                            formattedDate = new Date(timestamp).toLocaleDateString();
                        } catch (err) {
                            formattedDate = "时间格式错误";
                        }

                        const commentElement = document.createElement("div");
                        commentElement.className = "comment";
                        commentElement.innerHTML = `
                            <div class="comment-header">
                                <strong>用户：${item.username}</strong>
                                <span class="review-date">${formattedDate}</span>
                            </div>
                            <div class="comment-content">${item.comment}</div>
                            <div class="rating">${renderStars(item.rating)}</div>
                        `;
                        commentsContainer.appendChild(commentElement);
                    });

                    if (reviews.length > 3) {
                        moreReviewsBtn.classList.remove("hidden");
                    } else {
                        moreReviewsBtn.classList.add("hidden");
                    }
                }
            }


            // 渲染星级评分
            function renderStars(rating) {
                return Array.from({ length: 5 }, (_, i) =>
                    i < rating ? `<span class="star filled">★</span>` : `<span class="star">☆</span>`
                ).join("");
            }

            // 更多书评
            moreReviewsBtn.addEventListener("click", () => {
                fetch(`/api/reviews/${bookId}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // 清空现有评论
                            allCommentsContainer.innerHTML = "";

                            // 遍历评论数据，渲染到页面
                            data.reviews.forEach(({ rating, comment, username, created_at }) => {
                                // 时间戳处理逻辑
                                let formattedTime;
                                try {
                                    const timestamp = typeof created_at === "number" && created_at.toString().length === 10
                                        ? created_at * 1000
                                        : created_at;
                                    formattedTime = new Date(timestamp).toLocaleString();
                                } catch (err) {
                                    formattedTime = "时间格式错误";
                                }

                                // 创建评论元素
                                const commentElement = document.createElement("div");
                                commentElement.className = "comment";
                                commentElement.innerHTML = `
                                    <div class="comment-header">
                                        <strong>用户：${username}</strong>
                                        <span class="timestamp">${formattedTime}</span>
                                    </div>
                                    <div class="comment-content">${comment}</div>
                                    <div class="rating">${renderStars(rating)}</div>
                                `;
                                allCommentsContainer.appendChild(commentElement);
                            });

                            // 显示模态框
                            moreReviewsModal.classList.remove("hidden");
                        } else {
                            console.error("评论加载失败，数据错误");
                        }
                    })
                    .catch(err => console.error("加载评论失败", err));
            });


            // 关闭弹窗
            closeReviewsModal.addEventListener("click", () => {
                moreReviewsModal.classList.add("hidden");
            });

            // 打开评论弹窗
            addCommentButton.addEventListener("click", () => {
                addCommentModal.classList.remove("hidden");
            });

            // 关闭评论弹窗
            closeModal.addEventListener("click", () => {
                addCommentModal.classList.add("hidden");
            });

            // 提交评论
submitReviewBtn.addEventListener("click", () => {
    const ratingValue = parseInt(ratingInput.value, 10);
    const commentText = commentInput.value.trim();

    if (!ratingValue || ratingValue < 1 || ratingValue > 5) {
        alert("评分范围应在 1~5 之间！");
        return;
    }
    if (!commentText) {
        alert("评论内容不能为空！");
        return;
    }

    const payload = { book_id: bookId, rating: ratingValue, comment: commentText };

    fetch("/api/reviews", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
    })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                alert("评论发布成功！");
                ratingInput.value = 5;
                commentInput.value = "";

                // 关闭评论弹窗
                addCommentModal.classList.add("hidden");

                // 重新加载评论
                fetch(`/api/reviews/${bookId}`)
                    .then(res => res.json())
                    .then(data => {
                        if (data.success) renderReviews(data.reviews);
                    });
            } else {
                alert(data.message || "评论发布失败");
            }
        })
        .catch(err => console.error("提交评论出错:", err));
});
        });
    </script>
</body>
</html>
